package 面试;

import java.util.ArrayList;
import java.util.List;

public class 全排列 {

    public static List<List<Integer>> sort(int[] nums) {
        if (nums.length == 0)
            return null;
        List<List<Integer>> ans = new ArrayList<>();
        backTrace(ans, new ArrayList<>(), nums, new boolean[nums.length]);
        return ans;
    }

    public static void backTrace(List<List<Integer>> ans, List<Integer> temp,
                                 int[] nums, boolean[] used) {
        if (temp.size() == nums.length) {
            ans.add(new ArrayList<>(temp));
        }
        for (int i = 0; i < nums.length; i++) {
            if (used[i])
                continue;
            used[i] = true;
            temp.add(nums[i]);
            backTrace(ans, temp, nums, used);
            used[i] = false;
            temp.remove(temp.size()-1);

        }
    }

    public static void main(String[] args) {
        int[] nums = {1,2,3};
        List<List<Integer>> ans = sort(nums);
        ans.forEach((e) -> System.out.println(e));
    }

}
